package org.igeek.atomqq.task;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import org.igeek.atomqq.activity.BaseActivity;
import org.igeek.atomqq.net.HttpConnection;
import org.igeek.atomqq.net.HttpConnection.Request_TYPE;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.util.URLManager;
import org.json.JSONException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


/**
 * 获取验证码
 * 正常返回类型: application/x-javascript
 * @author hangxin1940@gmail.com
 * @version 创建时间：2012-1-29 下午1:32:26
 * 
 */
public class CheckcodeStringTask extends SingleAsyncTask<Void,Void,Void>{
	private TaskResultListener listener;
	private Response response;
	private String uin;
	private int flag;
	
	private Handler handler=new Handler(){
		
		
		@Override
		public void handleMessage(Message msg) {
			
			activity.showDialog(BaseActivity.DIALOG_ERROR, msg.getData());
		}
	};
	
	private BaseActivity activity;
	
	public CheckcodeStringTask(BaseActivity activity){
		this.activity=activity;
	}
	
	public void setOnTaskResult(TaskResultListener listener,int flag){
		this.listener=listener;
		this.flag=flag;
	}
	
	public void setParams(String uin){
		this.uin=uin;
	}

	@Override
	protected Void doInBackground(Void... params) {
		String surl=URLManager.CHECK_CODE+"?appid=1003903&uin=" + uin;
		try {
			URL url = new URL(surl);
			
			HttpConnection conn=new HttpConnection(url, Request_TYPE.GET);
			conn.setReferer(URLManager.REFER_ui_ptlogin2_qq_com_login);
			conn.connect();
			response=conn.getResponse();
			conn.disconnect();
			
			
			
		}catch (UnknownHostException e) {
			e.printStackTrace();
			showErrorDialog("网络异常");
		}catch (MalformedURLException e) {
			e.printStackTrace();
			showErrorDialog("连接出错");
		} catch (IOException e) {
			e.printStackTrace();
			showErrorDialog("数据读取异常");
		} catch (JSONException e) {
			e.printStackTrace();
			showErrorDialog("服务器返回出错");
		}
		
		
		return null;
	}

	
	
	private void showErrorDialog(String message){
		Bundle bundle=new Bundle();
		bundle.putString(BaseActivity.FLAG_ERROR, message);
		
		Message msg=new Message();
		msg.setData(bundle);
		handler.sendMessage(msg );
	}
	
	@Override
	protected void onPostExecute(Void result) {
		listener.onTaskResult(response,flag);
	}	



}
